package com.googlecode.jmxlogger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;

import com.googlecode.jmxlogger.model.JmxProcess;
import com.googlecode.jmxlogger.util.JmxUtils;

/**
 * Main() class that takes an argument which is the directory 
 * to look in for files which contain json data that defines 
 * queries to run against JMX servers.
 * 
 * @author jon
 */
public class JmxLogger {
    private static File jsonDir = new File(".");
    
    /** */
    public static void main(String[] args) throws Exception {
        parseOptions(args);
        
        for (File file : getJsonFiles()) {
            JmxProcess process = JmxUtils.getJmxProcess(file);
            JmxUtils.prettyPrint(process);
            JmxUtils.execute(process);
        }
    }
    
    /** */
    private static void parseOptions(String[] args) throws Exception {
        CommandLineParser parser = new GnuParser();
        CommandLine cl = parser.parse(getOptions(), args);
        Option[] options = cl.getOptions();
        for (Option option : options) {
            if (option.getOpt().equals("j")) {
                File tmp = new File(option.getValue());
                if (!tmp.exists() && !tmp.isDirectory()) {
                    throw new RuntimeException("Path to json directory is invalid: " + tmp);
                }
                setJsonDir(tmp);
            }
        }
    }

    /** */
    public static Options getOptions() {
        Options options = new Options();
        options.addOption("j", true, "Directory where json configuration is stored. Default is .");
        return options;
    }

    /** */
    public static void setJsonDir(File jsonDir) {
        JmxLogger.jsonDir = jsonDir;
    }

    /** */
    public static File getJsonDir() {
        return jsonDir;
    }
    
    /**
     * Looks in the jsonDir for files that end with .json as the suffix.
     */
    private static List<File> getJsonFiles() {
        File[] files = jsonDir.listFiles();
        List<File> result = new ArrayList<File>();
        for (File file : files) {
            if (file.getName().endsWith(".json")) {
                result.add(file);
            }
        }
        return result;
    }
}
